<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WRX的文件处理工具(生成Excel)</title>
    <style>
        .form-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        form {
            width: 1200px; /* 表单宽度 */
            padding: 200px;
            border: 5px solid #ccc;
            border-radius: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            box-sizing: border-box;
        }

        /* 基本样式 */
        table {
            width: 100%;
            border-collapse: collapse; /* 使边框合并为一个 */
            margin: 50px 0; /* 上下边距 */
        }

        /* 单元格间距和填充 */
        th, td {
            padding: 15px;
            text-align: left;
            vertical-align: top; /* 顶部对齐 */
        }

        /* 边框样式 */
        th {
            background-color: #03ff29; /* 表头背景色 */
            border-bottom: 1px solid #ddd; /* 表头底部边框 */
        }

        td {
            border-bottom: 1px solid #dddddd; /* 单元格底部边框 */
        }

        /* 文本样式 */
        th, td {
            font-family: Arial, sans-serif; /* 字体 */
            font-size: 14px; /* 字体大小 */
            color: #333333; /* 文本颜色 */
        }

        /* 斑马条纹效果 */
        tr:nth-child(even) {
            background-color: #e9eeea; /* 偶数行背景色 */
        }

        /* 鼠标悬停效果 */
        tr:hover {
            background-color: #f1f1f1; /* 鼠标悬停时的背景色 */
        }
    </style>
    <script>
        //预览 不带均值
        document.addEventListener('DOMContentLoaded', function() {
            // 尝试从localStorage获取缓存的表单数据
            const cacheFindFolderPath = localStorage.getItem('findFolderPath');
            const cacheDependencyFilePath = localStorage.getItem('dependencyFilePath');
            const cacheTypeFilters = localStorage.getItem('typeFilters');

            // 如果存在缓存数据，则填充到表单中
            if (cacheFindFolderPath) {
                document.getElementById('findFolderPath').value = cacheFindFolderPath;
            }
            if (cacheDependencyFilePath) {
                document.getElementById('dependencyFilePath').value = cacheDependencyFilePath;
            }
            if (cacheTypeFilters) {
                document.getElementById('typeFilters').value = cacheTypeFilters;
            }

            document.getElementById('search').addEventListener('click', function(event) {
                // 检查表单是否有效
                const form = document.getElementById('jsonForm');
                if (!form.checkValidity()) {
                    // 如果表单无效，则阻止提交
                    event.preventDefault();
                    // 显示表单校验错误
                    form.reportValidity();
                }
                event.preventDefault(); // 阻止表单的默认提交行为
                var findFolderPath = document.getElementById('findFolderPath').value;
                var dependencyFilePath = document.getElementById('dependencyFilePath').value;
                var typeFilters = document.getElementById('typeFilters').value.split(',');
                var data = {
                    findFolderPath: findFolderPath,
                    dependencyFilePath: dependencyFilePath,
                    typeFilters: typeFilters
                };

                // 将数据存储到localStorage
                localStorage.setItem('findFolderPath', findFolderPath);
                localStorage.setItem('dependencyFilePath', dependencyFilePath);
                localStorage.setItem('typeFilters', typeFilters);


                // 清空现有表格内容
                clearTable('dataTable');

                // 使用fetch发送POST请求
                fetch('http://localhost:8088/ncse/preview', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log('Success:', data);
                        // 处理响应数据...
                        handleResponse(data); // 调用处理响应的方法
                    })
                    .catch((error) => {
                        console.error('Error:', error);
                    });

        })});
        //预览 带均值
        document.addEventListener('DOMContentLoaded', function() {
            // 尝试从localStorage获取缓存的表单数据
            const cacheFindFolderPath = localStorage.getItem('findFolderPath');
            const cacheDependencyFilePath = localStorage.getItem('dependencyFilePath');
            const cacheTypeFilters = localStorage.getItem('typeFilters');

            // 如果存在缓存数据，则填充到表单中
            if (cacheFindFolderPath) {
                document.getElementById('findFolderPath').value = cacheFindFolderPath;
            }
            if (cacheDependencyFilePath) {
                document.getElementById('dependencyFilePath').value = cacheDependencyFilePath;
            }
            if (cacheTypeFilters) {
                document.getElementById('typeFilters').value = cacheTypeFilters;
            }

            document.getElementById('caculateAvg').addEventListener('click', function(event) {
                // 检查表单是否有效
                const form = document.getElementById('jsonForm');
                if (!form.checkValidity()) {
                    // 如果表单无效，则阻止提交
                    event.preventDefault();
                    // 显示表单校验错误
                    form.reportValidity();
                }
                event.preventDefault(); // 阻止表单的默认提交行为
                var findFolderPath = document.getElementById('findFolderPath').value;
                var dependencyFilePath = document.getElementById('dependencyFilePath').value;
                var typeFilters = document.getElementById('typeFilters').value.split(',');
                var data = {
                    findFolderPath: findFolderPath,
                    dependencyFilePath: dependencyFilePath,
                    typeFilters: typeFilters
                };

                // 将数据存储到localStorage
                localStorage.setItem('findFolderPath', findFolderPath);
                localStorage.setItem('dependencyFilePath', dependencyFilePath);
                localStorage.setItem('typeFilters', typeFilters);


                // 清空现有表格内容
                clearTable('dataTable');

                // 使用fetch发送POST请求
                fetch('http://localhost:8088/ncse/preivewExcelWithAvg', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log('Success:', data);
                        // 处理响应数据...
                        handleResponse(data); // 调用处理响应的方法
                    })
                    .catch((error) => {
                        console.error('Error:', error);
                    });

            })});
        function handleResponse(responseData) {
            // 这里添加处理响应数据的代码
            console.log('Received data:', responseData);
            // const data = JSON.parse(responseData);
            // 获取表格的thead和tbody元素
            const thead = document.getElementById('dataTable').getElementsByTagName('thead')[0];
            const tbody = document.getElementById('dataTable').getElementsByTagName('tbody')[0];
            // 确定列标题
            const columns = new Set();
            responseData.forEach(item => {
                Object.keys(item).forEach(key => columns.add(key));
            });

            // 创建列标题行
            const headerRow = thead.insertRow();
            columns.forEach(column => {
                const headerCell = document.createElement('th');
                headerCell.textContent = column;
                headerRow.appendChild(headerCell);
            });

            // 遍历数据并填充表格
            responseData.forEach(item => {
                const row = tbody.insertRow();
                columns.forEach(column => {
                    const cell = row.insertCell();
                    cell.textContent = item[column];
                });
            });
        }
        //导出不带均值
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('export').addEventListener('click', function(event) {
                const form = document.getElementById('jsonForm');
                // 检查表单是否有效
                if (!form.checkValidity()) {
                    // 如果表单无效，则阻止提交
                    event.preventDefault();
                    // 显示表单校验错误
                    form.reportValidity();
                }

                event.preventDefault(); // 阻止表单的默认提交行为

                var findFolderPath = document.getElementById('findFolderPath').value;
                var dependencyFilePath = document.getElementById('dependencyFilePath').value;
                var typeFilters = document.getElementById('typeFilters').value.split(',');

                var data = {
                    findFolderPath: findFolderPath,
                    dependencyFilePath: dependencyFilePath,
                    typeFilters: typeFilters
                };
                let fileName = 'default_filename.xlsx'
                fetch('http://localhost:8088/ncse/export', {
                    method: 'POST', // 设置请求方法为POST
                    headers: {
                        'Content-Type': 'application/json' // 设置请求头部为application/json
                    },
                    body: JSON.stringify(data) // 将JavaScript对象转换为JSON字符串
                })
                .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok ' + response.statusText);
                        }

                        // 尝试从Content-Disposition头中获取文件名
                        const disposition = response.headers.get('Content-Disposition');
                        fileName = disposition && disposition.match(/filename[^;]*;?/);
                        fileName = fileName && fileName[0].replace(/filename[^;]*=/, '');
                        if (fileName) {
                            fileName = decodeURIComponent(fileName);
                        }
                        // 如果没有在Content-Disposition头中找到文件名，可以使用默认文件名或进一步处理
                        if (!fileName) {
                            fileName = 'default_filename.xlsx'; // 这里的默认文件名应根据实际情况设置
                        }
                        return response.blob(); // 获取Blob
                    })
                    .then(blob => {
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.style.display = 'none';
                        a.href = url;
                        a.download = fileName; // 使用从响应头获取的文件名
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url); // 清理
                        document.body.removeChild(a);
                    })
                    .catch((error) => {
                        console.error('Error:', error);
                        // 在这里处理错误
                    });
            });
        });
        //导出带均值
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('exportCaculateAvg').addEventListener('click', function(event) {
                const form = document.getElementById('jsonForm');
                // 检查表单是否有效
                if (!form.checkValidity()) {
                    // 如果表单无效，则阻止提交
                    event.preventDefault();
                    // 显示表单校验错误
                    form.reportValidity();
                }

                event.preventDefault(); // 阻止表单的默认提交行为

                var findFolderPath = document.getElementById('findFolderPath').value;
                var dependencyFilePath = document.getElementById('dependencyFilePath').value;
                var typeFilters = document.getElementById('typeFilters').value.split(',');

                var data = {
                    findFolderPath: findFolderPath,
                    dependencyFilePath: dependencyFilePath,
                    typeFilters: typeFilters
                };
                let fileName = 'default_filename.xlsx'
                fetch('http://localhost:8088/ncse/exportExcelWithAvg', {
                    method: 'POST', // 设置请求方法为POST
                    headers: {
                        'Content-Type': 'application/json' // 设置请求头部为application/json
                    },
                    body: JSON.stringify(data) // 将JavaScript对象转换为JSON字符串
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok ' + response.statusText);
                        }

                        // 尝试从Content-Disposition头中获取文件名
                        const disposition = response.headers.get('Content-Disposition');
                        fileName = disposition && disposition.match(/filename[^;]*;?/);
                        fileName = fileName && fileName[0].replace(/filename[^;]*=/, '');
                        if (fileName) {
                            fileName = decodeURIComponent(fileName);
                        }
                        // 如果没有在Content-Disposition头中找到文件名，可以使用默认文件名或进一步处理
                        if (!fileName) {
                            fileName = 'default_filename.xlsx'; // 这里的默认文件名应根据实际情况设置
                        }
                        return response.blob(); // 获取Blob
                    })
                    .then(blob => {
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.style.display = 'none';
                        a.href = url;
                        a.download = fileName; // 使用从响应头获取的文件名
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url); // 清理
                        document.body.removeChild(a);
                    })
                    .catch((error) => {
                        console.error('Error:', error);
                        // 在这里处理错误
                    });
            });
        });
        //清空
        function clearTable(tableId) {
            const table = document.getElementById(tableId);
            // 假设表格的tbody具有id为"tableBody"的元素
            const tbody = table.getElementsByTagName('tbody')[0];
            const thead = table.getElementsByTagName('thead')[0];
            while (thead.rows.length > 0) {
                thead.removeChild(thead.rows[0]);
            }
            // 清空tbody中的所有行
            while (tbody.rows.length > 0) {
                tbody.removeChild(tbody.rows[0]);
            }
        }
    </script>
</head>
<body>
<!-- 定义一个表单，但不设置action属性，因为我们将使用JavaScript处理提交 -->

<div class="container">
    <div class="form-container">
        <form id="jsonForm" onsubmit="return false;">
            <label for="findFolderPath">扫描的文件夹绝对路径（可嵌套）:</label>
            <input type="text" id="findFolderPath" style="width: 800px;" width="100px" name="findFolderPath" placeholder="注意文件地址分隔符" required><br><br>

            <label for="dependencyFilePath">配置文件绝对路径 :</label>
            <input type="text" id="dependencyFilePath" style="width: 800px;" name="dependencyFilePath" placeholder="注意文件地址分隔符" required><br><br>

            <label for="typeFilters">要过滤的文件格式:</label>
            <input type="text" id="typeFilters" style="width: 800px;"  name="typeFilters" placeholder=".log"><br><br>

            <!-- 一个按钮，用于触发JavaScript提交表单 -->
            <button type="button" id="search" style="width: 150px;" >查询</button>
            <button type="button" id="caculateAvg" style="width: 150px;" >计算均值</button>
            <button type="button" id="export" style="width: 150px;" >导出</button>
            <button type="button" id="exportCaculateAvg" style="width: 150px;" >导出均值</button>
        </form>
    </div>

    <table id="dataTable">
        <thead>
        <tr>
            <!-- 动态列标题将被插入这里 -->
        </tr>
        </thead>
        <tbody>
        <!-- 数据将被动态插入这里 -->
        </tbody>
    </table>
</div>


</body>
</html>